package com.jintoufs.weixin.tour;

import com.google.common.collect.Maps;
import com.jintoufs.domain.bill.BillInfo;
import com.jintoufs.domain.category.Category;
import com.jintoufs.domain.constants.Constants;
import com.jintoufs.domain.constants.FullCalendar;
import com.jintoufs.domain.constants.MessageConstants;
import com.jintoufs.domain.coupon.Coupon;
import com.jintoufs.domain.customer.Customer;
import com.jintoufs.domain.customer.CustomerCoupon;
import com.jintoufs.domain.images.Images;
import com.jintoufs.domain.tour.TourRoute;
import com.jintoufs.domain.tour.TourRouteDayDetail;
import com.jintoufs.domain.tour.TourRouteOrder;
import com.jintoufs.domain.tour.TourRoutePrice;
import com.jintoufs.interceptor.ParamCheck;
import com.jintoufs.service.banner.BannerService;
import com.jintoufs.service.bill.BillService;
import com.jintoufs.service.category.CategoryService;
import com.jintoufs.service.contacts.ContactsService;
import com.jintoufs.service.coupon.CouponService;
import com.jintoufs.service.customer.CustomerCouponService;
import com.jintoufs.service.image.ImageService;
import com.jintoufs.service.tour.TourRouteService;
import com.jintoufs.util.date.DateUtils;
import com.jintoufs.util.valid.ValidUtil;
import com.jintoufs.weixin.SupportAction;
import org.cosmos.modules.exception.ServiceException;
import org.cosmos.modules.web.msg.AjaxMsg;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by yangpeng on 2018/1/22.
 */
@RestController
@RequestMapping("/api")
public class TourAction extends SupportAction {
    @Resource
    private ContactsService contactsService;
    @Resource
    private TourRouteService tourRouteService;

    @Resource
    private BannerService bannerService;

    @Resource
    private ImageService imageService;

    @Resource
    private CategoryService categoryService;

    @Resource
    private CustomerCouponService customerCouponService;

    @Resource
    private CouponService couponService;

    @Resource
    BillService billService;

    @GetMapping("/tour/index")
    public AjaxMsg tourIndex(Integer pageSize,Integer pageNum){
        AjaxMsg ajaxMsg = new AjaxMsg();
        try {
            Map<String, Object> result = new HashMap<>();
            Map<String, Object> map = new HashMap<>();
            //查询banner
            map.put("typeId", Constants.BANNER_TYPE_ROUTE);
            List<Map<String, Object>> banners = bannerService.queryByParams(map);
            //查询推荐线路
            map.clear();
//            map.put("recommend",Constants.PRODUCT_RECOMMEND);
            map.put("status",Constants.RES_STATUS_NORMAL);
            map.put("pageStart",(pageNum-1)*pageSize);
            map.put("pageSize", pageSize);
            List<Map<String, Object>> tourList = tourRouteService.getByParams(map);
            //查询线路分类
            map.clear();
            map.put("parentId", "1005002");
            List<Category> categoryList= categoryService.queryByParams(map);
            result.put("banner", banners);
            result.put("tourList", tourList);
            result.put("category", categoryList);
            ajaxMsg.setDatas(result);
        } catch (Exception e) {
            e.printStackTrace();
            ajaxMsg.setMessage("error");
            ajaxMsg.setCode(AjaxMsg.FAILURE);
        }
        return ajaxMsg;
    }

    @GetMapping("/tour/more")
    public AjaxMsg moreTour(Integer pageNum,Integer pageSize){
        AjaxMsg ajaxMsg = new AjaxMsg();
        Map map = new HashMap();
        map.put("status",Constants.RES_STATUS_NORMAL);
        map.put("pageStart",(pageNum-1)*pageSize);
        map.put("pageSize", pageSize);
        List<Map<String, Object>> tourList = tourRouteService.getByParams(map);
        ajaxMsg.setDatas(tourList);
        return ajaxMsg;
    }

    @ParamCheck(params = "id")
    @GetMapping("/tour/detail")
    public AjaxMsg tourDetail(String id) {
        AjaxMsg ajaxMsg = new AjaxMsg();
        Map result = new HashMap();
        Map params = new HashMap();
        Map tourDetail = new HashMap();
        List<Map> tours = null;
        List<String> images = new ArrayList<>();
        params.put("id", id);
        try {
            tours = tourRouteService.getByParams(params);
            if (!ValidUtil.isEmpty(tours) && tours.size() > 0) {
                tourDetail = tours.get(0);
                //查询行程的所有天
                List<Map<String,Object>> tourDays = tourRouteService.getTourDayByRouteId(id);
                for (Map m : tourDays) {
                    String dayId = (String) m.get("id");
                    //查询一天的所有活动详情
                    List<TourRouteDayDetail> details = tourRouteService.getRouteDayDetailsByDayId(dayId);
                    m.put("dayDetails", details);
                }
                tourDetail.put("tourDays", tourDays);
                //查询图片
                params.clear();
                params.put("valueId", id);
                List<Images> imagesList = imageService.selectByparams(params);
                for (Images i : imagesList) {
                    images.add(i.getPath());
                }
                result.put("tour", tourDetail);
                result.put("images", images);
                ajaxMsg.setDatas(result);
            } else {
                throw new RuntimeException("未查询到数据");
            }
        } catch (Exception e) {
            e.printStackTrace();
            ajaxMsg.setCode(AjaxMsg.FAILURE);
            ajaxMsg.setMessage(MessageConstants.SYSTEM_ERROR_MESSAGE);
            return ajaxMsg;
        }
        return ajaxMsg;
    }

    @GetMapping("/tour/dayDetail")
    public AjaxMsg getDayDetail(String id){
        AjaxMsg ajaxMsg = new AjaxMsg();
        TourRouteDayDetail tourRouteDayDetail = null;
        try {
            tourRouteDayDetail= tourRouteService.getRouteDayDetailByDetailId(id);
        } catch (Exception e) {
            e.printStackTrace();
            ajaxMsg.setCode(AjaxMsg.FAILURE);
            ajaxMsg.setMessage(MessageConstants.SYSTEM_ERROR_MESSAGE);
            return ajaxMsg;
        }
        ajaxMsg.setDatas(tourRouteDayDetail);
        return ajaxMsg;
    }

    @GetMapping("/tour/search")
    public AjaxMsg searchTour(Integer pageSize, Integer pageNum,
                              String orderType,String isDesc,String keyword,String typeId,boolean selfSupport){
        AjaxMsg ajaxMsg = new AjaxMsg();
        Map params = new HashMap(10);
        List<Map> tours = null;
        try {
            if (Constants.ORDER_PRICE.equals(orderType)) {
                //使用价格排序
                params.put("price", "price");
                if ("desc".equals(isDesc)) {
                    params.put("isDesc", isDesc);
                }
            }
            Integer pageStart = (pageNum-1)*pageSize;
            params.put("pageStart", pageStart);
            params.put("pageSize", pageSize);
            params.put("routeName", keyword);
            if(selfSupport){
                params.put("selfSupport", selfSupport);
            }
            if (!ValidUtil.isEmpty(typeId)) {
                params.put("typeId", typeId);
            }
            params.put("status",Constants.CUSTOMER_AUTH_STATUS_AUTHED);
            tours= tourRouteService.getByParams(params);
        } catch (Exception e) {
            e.printStackTrace();
            ajaxMsg.setCode(AjaxMsg.FAILURE);
            ajaxMsg.setMessage(MessageConstants.SYSTEM_ERROR_MESSAGE);
            return ajaxMsg;
        }

        ajaxMsg.setDatas(tours);
        return ajaxMsg;
    }

    /**
     * 获取以当前时间为准，不同时间段内订购指定线路的价格列表
     * @param id 线路ID
     * @return List<FullCalendar>
     */
    @GetMapping("/tour/dayOrderPrice")
    public AjaxMsg getDayOrderPrice(String id){
        AjaxMsg ajaxMsg = new AjaxMsg();
        List<FullCalendar> fullCalendars;
        try {
            Calendar calendar = Calendar.getInstance();
            Map<String,Object> params = Maps.newHashMap();
            params.put("tourRouteId",id);
            //获取从当前时间开始，往后15天内的线路价格
            calendar.add(Calendar.DATE, 1);
            params.put("start",calendar.getTime());
            calendar.add(Calendar.DATE,15);
            params.put("end",calendar.getTime());
            fullCalendars = tourRouteService.getPriceCalendarForWeixin(params);
            ajaxMsg.setCode(AjaxMsg.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            ajaxMsg.setCode(AjaxMsg.FAILURE);
            ajaxMsg.setMessage(MessageConstants.SYSTEM_ERROR_MESSAGE);
            return ajaxMsg;
        }
        ajaxMsg.setDatas(fullCalendars);
        return ajaxMsg;
    }

    @GetMapping("/tour/dayPrice")
    public AjaxMsg getDayPrice(String id){
        AjaxMsg ajaxMsg = new AjaxMsg();
        List<Map<String,Object>> fullCalendars;
        try {
            Calendar calendar = Calendar.getInstance();
            Map<String,Object> params = Maps.newHashMap();
            params.put("tourRouteId",id);
            //获取从当前时间开始，往后15天内的线路价格
            calendar.add(Calendar.DATE, 1);
            params.put("start",calendar.getTime());
            calendar.add(Calendar.DATE,15);
            params.put("end",calendar.getTime());
            fullCalendars = tourRouteService.queryPriceByParams(params);
            ajaxMsg.setCode(AjaxMsg.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            ajaxMsg.setCode(AjaxMsg.FAILURE);
            ajaxMsg.setMessage(MessageConstants.SYSTEM_ERROR_MESSAGE);
            return ajaxMsg;
        }
        ajaxMsg.setDatas(fullCalendars);
        return ajaxMsg;
    }

    /**
     * 获取以当前时间为准，不同时间段内订购指定线路的价格列表
     * @param startDate 订单开始时间
     * @param id 线路ID
     * @param userInfo 订单人员信息,JSON字符串
     *                 格式：[{name:旅行者姓名,idCard:身份证号码,tel:电话}...]
     * @param couponId 优惠券id
     * @param token 用户token
     * @param number 数量
     */
    @GetMapping("/tour/order")
    public AjaxMsg order(String startDate,String id, String userInfo,String couponId,
                         String token,String number,String remark,String companyName,
                         String code,String address,String contactName,String contactTel){
        AjaxMsg ajaxMsg = new AjaxMsg();
        try {
            // 验证用户token
            Customer customer = getCustomerByToken(token);
            if (ValidUtil.isEmpty(customer)) {
                ajaxMsg.setCode(AjaxMsg.FAILURE);
                ajaxMsg.setDatas(Constants.NOAUTH);
                return ajaxMsg;
            }else{
                // 优惠金额
                BigDecimal discount = new BigDecimal(0);
                CustomerCoupon customerCoupon = null;

                if(!ValidUtil.isEmpty(couponId)){
                    //现在只支持一份订单只使用一张优惠券
                    Map<String,Object> param = Maps.newHashMap();
                    param.put("customerId",customer.getId());
                    param.put("couponId",couponId);
                    List<CustomerCoupon> customerCoupons = customerCouponService.queryByParam(param);
                    if(customerCoupons !=null && customerCoupons.size()>0){
                        customerCoupon = customerCoupons.get(0);
                        if (customerCoupon.getUsedTime()==null){
                            Integer minReserve = tourRouteService.getMinReserve(id,startDate);
                            if (minReserve>=Integer.valueOf(number)){
                                Coupon coupon = couponService.getById(customerCoupon.getCouponId());
                                if(!Constants.COUPON_TYPE_TOUR.equals(coupon.getTypeId())){
                                    throw new ServiceException("优惠券类型不匹配");
                                }
                                Date now = new Date();
                                if(coupon.getSendStartDate().before(now) && coupon.getSendEndDate().after(now)){
                                    discount = coupon.getMaxAmount();
                                }else{
                                    customerCoupon = null;
                                    throw new ServiceException("优惠券当前不可用！");
                                }
                            }else {
                                throw new ServiceException("该线路在选择的日期没有多余的位置啦！");
                            }
                        }else{
                            customerCoupon = null;
                            throw new ServiceException("该优惠券已经使用过，不能重复使用！");
                        }
                    }else{
                        throw new ServiceException("该优惠券不存在或者不在使用期限内！");
                    }
                }

                TourRoute tourRoute = tourRouteService.getRouteById(id);


                if(tourRoute == null){
                    ajaxMsg.setMessage("未找到指定的线路信息！");
                    ajaxMsg.setCode(AjaxMsg.FAILURE);
                }else {
                    // 获取所下订单日子的线路价格
                    Map<String,Object> params = Maps.newHashMap();
                    params.put("tourRouteId",id);
                    params.put("start",startDate);
//                params.put("end",startDate);
                    TourRoutePrice tourRoutePrices = tourRouteService.getTourRoutePrice(params);
                    // 线路价格
                    if (tourRoutePrices==null){
                        tourRoutePrices = new TourRoutePrice();
                        tourRoutePrices.setId(getUUID());
                        tourRoutePrices.setTourRouteId(id);
                        tourRoutePrices.setPrice(tourRoute.getTotalFee());
                        tourRoutePrices.setDate(DateUtils.stringToDate(startDate));
                        tourRoutePrices.setDistributionPrice(tourRoute.getDistributionPrice());
                        tourRoutePrices.setReserve(tourRoute.getPersonNum()-Integer.valueOf(number));
                        tourRouteService.insertTourRoutePrice(tourRoutePrices);
                    }else {
                        if(tourRoutePrices.getReserve()!=null){
                            tourRoutePrices.setReserve(tourRoutePrices.getReserve()-Integer.valueOf(number));
                        }
                        tourRouteService.updateTourRoutePrice(tourRoutePrices);
                    }
                    BigDecimal price = tourRoutePrices.getPrice();

                    TourRouteOrder tourRouteOrder = new TourRouteOrder();
                    String tourRouteOrderId  = getUUID();
                    tourRouteOrder.setId(tourRouteOrderId);
                    tourRouteOrder.setContactName(contactName);
                    tourRouteOrder.setContactTel(contactTel);
                    tourRouteOrder.setModifyTime(new Date());
                    BillInfo billInfo = null;
                    if (!ValidUtil.isEmpty(companyName)) {
                        //需要发票
                        tourRouteOrder.setNeedBill("1");
                        billInfo = new BillInfo();
                        billInfo.setId(getUUID());
                        billInfo.setOrderId(tourRouteOrderId);
                        billInfo.setCode(code);
                        billInfo.setAdress(address);
                        billInfo.setCompanyName(companyName);
                        billInfo.setName(customer.getRealName());
                        billInfo.setTel(customer.getMobilePhone());
//                        billService.saveBillInfo(billInfo);
                    }
                    //设置订单优惠后的价格
                    tourRouteOrder.setPrice(price.multiply(new BigDecimal(number)).subtract(discount));
                    //设置订单原价格
                    tourRouteOrder.setActPrice(price.multiply(new BigDecimal(number)));
                    //设置分销价格
                    tourRouteOrder.setSharePrice(tourRoutePrices.getDistributionPrice().multiply(new BigDecimal(number)));
                    tourRouteOrder.setTourRouteId(id);
                    tourRouteOrder.setStartDate(new SimpleDateFormat("yyyy-MM-dd").parse(startDate));
                    tourRouteOrder.setEndDate(DateUtils.addDays(tourRouteOrder.getStartDate(),tourRoute.getTourDay()));
                    tourRouteOrder.setCustomerCouponId(customerCoupon==null?null:couponId);
                    tourRouteOrder.setAgencyId(tourRoute.getTravelAgencyId());
                    tourRouteOrder.setDistributorId(customer.getDistributorId());
                    tourRouteOrder.setSpreadId(customer.getRecommendId());
                    tourRouteOrder.setCustomerId(customer.getId());
                    tourRouteOrder.setNumber(Integer.valueOf(number));
                    tourRouteOrder.setStatus("0");
                    tourRouteOrder.setInTime(new Date());
                    tourRouteOrder.setRecommendId(customer.getRecommendId());
                    tourRouteOrder.setSpreadId(customer.getSpreadId());
                    tourRouteOrder.setRemark(ValidUtil.isEmpty(remark)?"无":remark);
                    tourRouteService.order(tourRouteOrder,customerCoupon,userInfo,billInfo,customer.getId());
                    ajaxMsg.setCode(AjaxMsg.SUCCESS);
                    ajaxMsg.setDatas(tourRouteOrder);
                }

            }

        } catch (ServiceException se){
            se.printStackTrace();
            ajaxMsg.setCode(AjaxMsg.FAILURE);
            ajaxMsg.setMessage(se.getMessage());
        }catch (Exception e) {
            e.printStackTrace();
            ajaxMsg.setCode(AjaxMsg.FAILURE);
            ajaxMsg.setMessage(MessageConstants.SYSTEM_ERROR_MESSAGE);
            return ajaxMsg;
        }
        return ajaxMsg;
    }
}
